package com.keliangliu.demo.lock;

import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TaskTest {


    private static final int DATA_NUM = 1955615;



    private static final int THREAD_NUM = 8;
    private static ExecutorService executorService = Executors.newFixedThreadPool(THREAD_NUM);
    private static  CountDownLatch countDownLatch = new CountDownLatch(THREAD_NUM);



    public static void main(String[] args) throws InterruptedException {

        Long startTime = System.currentTimeMillis();
        //首先分配线程的数量
        int perSize = DATA_NUM / THREAD_NUM;
        int start = 1;
        Map<Integer,Integer> map = new LinkedHashMap<>();
        for(int i = 1; i <= THREAD_NUM; i++) {
            int end = 0;
            if(i == THREAD_NUM) {
                end = DATA_NUM;

            }else {
                end = start + perSize;
            }
            map.put(start,end);
            start = end + 1;
        }
        for(Map.Entry<Integer,Integer> entry : map.entrySet()) {
            executorService.submit(new AyncDataTest(entry.getKey(),entry.getValue()));
        }

        countDownLatch.await();
//        Long endTime = System.currentTimeMillis();
//        System.out.println("执行完毕:" + (endTime - startTime));

//        for(int i = 1; i <= DATA_NUM; i++) {
//            System.out.println(i);
//        }
        Long endTime = System.currentTimeMillis();
        System.out.println("执行完毕:" + (endTime - startTime));
    }


    public static class AyncDataTest extends Thread {


        private int start;

        private int end;

        public AyncDataTest(int start, int end) {
            this.start = start;
            this.end = end;

        }


        @Override
        public void run() {
            for(int i = start; i <= end; i++) {
                System.out.println(Thread.currentThread().getName()+ "执行：" + i);

            }
            countDownLatch.countDown();
        }
    }






}
